<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="基础表单">
        基础表单，用于向用户收集表单信息，并展示 Password，BasicSelect，TableSelect，
        组件使用示例</n-card
      >
    </div>
    <n-card :bordered="false" class="mt-3 proCard">
      <div class="BasicForm">
        <BasicForm
          ref="basicFormRef"
          submitButtonText="提交预约"
          layout="horizontal"
          :gridProps="{ cols: 1 }"
          :schemas="schemas"
          @submit="handleSubmit"
          @reset="handleReset"
        >
          <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
          </template>

          <template #passwordSlot="{ model, field }">
            <Password
              ref="passwordRef"
              v-model:value="model[field]"
              @change="changePassword"
              block
              repeat
            />
          </template>
          <!-- 回显赋值 仅显示在选择器中 -->
          <!-- v-model:value="people" -->
          <template #peopleSlot="{ model, field }">
            <TableSelect
              ref="TableSelectRef"
              labelField="name"
              valueField="id"
              placeholder="请选择内容（单选）"
              v-model:value="model[field]"
              width="100%"
              :tableProps="{
                rowKey: (row) => row.id,
                request: loadDataTable,
                columns: columns,
                pagination: {
                  simple: true,
                },
              }"
              @change="tableSelectChange"
            />
          </template>
        </BasicForm>
      </div>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, unref, onMounted } from 'vue';
  import { TableSelect } from '@/components/TableSelect';
  import { BasicForm, FormSchema } from '@/components/Form/index';
  import { useMessage } from 'naive-ui';
  import { Password } from '@/components/Password';
  import { getTableList } from '@/api/table/list';
  import { columns } from '../tableSelect/basicColumns';

  import { getClassifyList } from '@/api/select/select';

  const basicFormRef = ref();
  const isMakeSource = ref(true);
  // const people = ref(['啊俊']); // 需要是数组格式

  const getIsMakeSource = computed(() => {
    return isMakeSource.value;
  });

  const params = {
    type: 1,
  };

  const loadDataTable = async (res) => {
    return await getTableList({ ...params, ...res });
  };

  async function loadSelectData(res) {
    //这里可以进行数据转换处理
    return (await getClassifyList({ ...res, ...params })).map((item, index) => {
      return {
        ...item,
        index,
      };
    });
  }

  const schemas: FormSchema[] = reactive([
    {
      field: 'id',
      defaultValue: 128,
      hidden: true,
    },
    {
      field: 'identity',
      defaultValue: '我是一个隐藏字段内容',
      hidden: true,
    },
    {
      field: 'name',
      component: 'NInput',
      label: '姓名',
      labelMessage: '这是一个提示',
      componentProps: {
        placeholder: '请输入姓名',
        onInput: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ required: true, message: '请输入姓名', trigger: ['blur'] }],
    },
    {
      field: 'user.basic.age',
      component: 'NInputNumber',
      label: '年龄',
      labelMessage: '这是一个field对象演示',
      componentProps: {
        placeholder: '请输入年龄',
      },
      rules: [{ required: true, type: 'number', message: '请输入年龄', trigger: ['blur'] }],
    },
    {
      field: 'mobile',
      component: 'NInputNumber',
      label: '手机',
      componentProps: {
        placeholder: '请输入手机号码',
        showButton: false,
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'type',
      component: 'NSelect',
      label: '类型',
      componentProps: {
        placeholder: '请选择类型',
        options: [
          {
            label: '舒适性',
            value: 1,
          },
          {
            label: '经济性',
            value: 2,
          },
        ],
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'classify',
      component: 'BasicSelect',
      label: '动态分类',
      componentProps: {
        placeholder: '请选择分类',
        request: loadSelectData,
        block: true,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ required: true, message: '请选择分类', trigger: ['change'] }],
    },
    {
      field: 'people',
      label: '选择人员',
      slot: 'peopleSlot',
      rules: [{ required: true, message: '请选择人员', trigger: ['change', 'blur'] }],
    },
    {
      field: 'makeDate',
      component: 'NDatePicker',
      label: '预约时间',
      defaultValue: 1183135260000,
      componentProps: {
        type: 'date',
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'makeTime',
      component: 'NTimePicker',
      label: '停留时间',
      componentProps: {
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'makeProject',
      component: 'NCheckbox',
      label: '预约项目',
      componentProps: {
        placeholder: '请选择预约项目',
        options: [
          {
            label: '种牙',
            value: 1,
          },
          {
            label: '补牙',
            value: 2,
          },
          {
            label: '根管',
            value: 3,
          },
        ],
        onUpdateValue: (e: any) => {
          // 动态切换 来源 表单是否显示
          isMakeSource.value = e.includes(3);
          basicFormRef.value.setSchema(getNewSchemas());
        },
      },
    },
    {
      field: 'makeSource',
      component: 'NRadioGroup',
      label: '来源',
      hidden: getIsMakeSource.value,
      componentProps: {
        options: [
          {
            label: '网上',
            value: 1,
          },
          {
            label: '门店',
            value: 2,
          },
        ],
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'status',
      label: '状态',
      //插槽
      slot: 'statusSlot',
    },
    {
      field: 'password',
      label: '密码',
      slot: 'passwordSlot',
    },
  ]);

  function getNewSchemas() {
    const newSchemas = unref(schemas);
    newSchemas.forEach((item) => {
      if (item.field === 'makeSource') {
        item.hidden = !isMakeSource.value;
      }
    });
    return newSchemas;
  }

  const message = useMessage();

  const passwordRef = ref();

  function handleSubmit(values: Recordable) {
    const isVal = passwordRef.value.isValidator();
    if (!isVal) {
      return passwordRef.value.showValidator();
    }
    message.success(JSON.stringify(values));
    console.log(values);
  }

  function handleReset(values: Recordable) {
    message.success(JSON.stringify(values));
  }

  function changePassword(value) {
    console.log(value);
  }

  function tableSelectChange(list) {
    console.log('list', list);
    const people = list.length ? [list[0].name] : [];
    basicFormRef.value.setFieldsValue({ people });
  }

  onMounted(() => {
    basicFormRef.value.setFieldsValue({
      user: {
        basic: {
          age: 4,
        },
      },
    });
  });
</script>

<style lang="less" scoped>
  .BasicForm {
    width: 550px;
    margin: 0 auto;
    overflow: hidden;
    padding-top: 20px;
  }
</style>
